import useEaseInOut from './easeInOut'

export interface BlockAutoScrollOption {
  id: string
  singleDuration?: number
}

function useBlockAutoScroll({id, singleDuration = 1000}: BlockAutoScrollOption) {
  const scrollBox = ref<HTMLElement | null>(null)
  const scrollContent = ref<HTMLElement | null>(null)

  // 数字曲线
  const {count, countStart} = useEaseInOut({
    startVal: 0,
    endVal: 0,
    autoplay: false,
    useEasing: false
  })

  function startScroll() {
    console.log('测试', scrollBox.value, scrollContent.value)

    if (scrollBox.value && scrollContent.value) {
      countStart({
        startVal: 0,
        endVal: scrollContent.value.offsetHeight,
        duration: scrollContent.value.childElementCount * singleDuration
      })
    }
  }

  watch(
    () => [scrollBox.value, scrollContent.value],
    n => {
      startScroll()
    }
  )

  watch(
    () => count.value,
    n => {
      console.log('测试', n)
      if (n) {
        console.log(scrollContent.value?.childElementCount)
        scrollContent.value?.scrollTo({top: Number(n)})
      }
    }
  )

  onUpdated(() => {
    nextTick(() => {
      const scrollBoxDom = document.getElementById(id)
      // 获取滚动内容的外框
      if (scrollBoxDom) {
        const scrollBoxDomHeight = scrollBoxDom.offsetHeight

        // 获取滚动内容
        const scrollContentDom = document.getElementById(id + '-' + 'CBC-scroll-content')
        if (scrollContentDom) {
          const scrollContentDomHeight = scrollContentDom.offsetHeight

          // 当滚动内容的高度大于滚动内容的外框高度时
          if (scrollContentDomHeight > scrollBoxDomHeight) {
            scrollBox.value = scrollBoxDom
            scrollContent.value = scrollContentDom
          }
        }
      }
    })
  })

  return {startScroll}
}

export default useBlockAutoScroll
